package com.sniper.web.freemarker;

import com.sniper.data.BaseData;
import com.sniper.utils.ValidateUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class ViewHomeUtils {

    public static String intToDateString(int dateInt) {
        return intToDateString(dateInt, BaseData.DATE_FORMAT);
    }

    public static String intToDateString(int dateInt, String format) {

        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        if (dateInt == 0) {
            return dateFormat.format(new Date());
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(dateInt * 1000L);
        return dateFormat.format(calendar.getTime());
    }

    public static int getTimeMillis(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return (int) (calendar.getTimeInMillis() / 1000L);
    }

    public static int getTimeMillis(String date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(BaseData.DATE_TIME_FORMAT);
        try {
            dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = dateFormat.getCalendar();
        return (int) (calendar.getTimeInMillis() / 1000L);
    }

    public static Date intToDate(int dateInt) {
        if (dateInt == 0) {
            return new Date();
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(dateInt * 1000L);
        return calendar.getTime();
    }

    public static Date intToDate(long dateInt) {
        if (dateInt == 0) {
            return new Date();
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(dateInt * 1000L);
        return calendar.getTime();
    }

    public static String image(String img) {
        if (ValidateUtil.isValid(img)) {
            if (img.startsWith("/")) {
                return img;
            } else {
                return "/public/attachments/" + img;
            }
        }
        return "";
    }

    public static String substr(String str, int limit) {
        if (str.length() > limit) {
            return str.substring(0, limit);
        }
        return str;
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(1433388531 * 1000L);
        SimpleDateFormat dateFormat = new SimpleDateFormat(BaseData.DATE_FORMAT);
        System.out.println(dateFormat.format(calendar.getTime()));

        System.out.println("yyyy-MM-dd".substring(0, 7).replace("_", ""));
    }

}
